package com.gitee.wsl.prism4j.languages

import com.gitee.wsl.prism4j.GrammarUtils
import com.gitee.wsl.prism4j.Prism4j
import com.gitee.wsl.prism4j.Prism4j.Companion.grammar
import com.gitee.wsl.prism4j.Prism4j.Companion.pattern
import com.gitee.wsl.prism4j.Prism4j.Companion.token
import com.gitee.wsl.prism4j.annotations.Modify
import com.gitee.wsl.prism4j.Prism4j.Pattern

@Suppress("unused")
@Modify("css")
object Prism_css_extras {
    fun create(prism4j: Prism4j): Prism4j.Grammar? {
        val css: Prism4j.Grammar? = prism4j.grammar("css")

        if (css != null) {
            val selector: Prism4j.Token? = GrammarUtils.findToken(css, "selector")
            if (selector != null) {
                val pattern: Pattern = pattern(
                    Pattern.compile("[^{}\\s][^{}]*(?=\\s*\\{)"),
                    false,
                    false,
                    null,
                    grammar(
                        "inside",
                        token(
                            "pseudo-element",
                            pattern(Pattern.compile(":(?:after|before|first-letter|first-line|selection)|::[-\\w]+"))
                        ),
                        token("pseudo-class", pattern(Pattern.compile(":[-\\w]+(?:\\(.*\\))?"))),
                        token("class", pattern(Pattern.compile("\\.[-:.\\w]+"))),
                        token("id", pattern(Pattern.compile("#[-:.\\w]+"))),
                        token("attribute", pattern(Pattern.compile("\\[[^\\]]+\\]")))
                    )
                )
                selector.patterns().clear()
                selector.patterns().add(pattern)
            }

            GrammarUtils.insertBeforeToken(
                css, "function",
                token(
                    "hexcode",
                    pattern(Pattern.compile("#[\\da-f]{3,8}", Pattern.CASE_INSENSITIVE))
                ),
                token(
                    "entity",
                    pattern(
                        Pattern.compile(
                            "\\\\[\\da-f]{1,8}",
                            Pattern.CASE_INSENSITIVE
                        )
                    )
                ),
                token("number", pattern(Pattern.compile("[\\d%.]+")))
            )
        }
        return null
    }
}
